<?php

namespace app\admin\controller;

use think\Request;
use think\Controller;
use think\Db;

class Upload extends Controller
{   


/*    public function index()
    {   
        $idnumber=Request::instance()->train('idnumber');
        $username=Request::instance()->train('name');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,text/html");
        $file = request()->file('file');
        if (!$file) {
          return resultArray(['error' => '未选择文件']);
        }
        $name = substr($file->getInfo()['name'], 0, strripos($file->getInfo()['name'], '.'));
        $filenameArr = explode ( '.', $file->getInfo()['name']); 
        $file_ext = strtolower ( $filenameArr [count ( $filenameArr ) - 1] );
        if($file_ext=='doc'||$file_ext=='docx')
        {
          $path1="uploads/".$idnumber;
          if(!file_exists($path1)){
          mkdir($path1,0777,true);
          chmod($path1,0777);
          }
          $info = $file->validate(['ext'=>'doc,docx'])->move(ROOT_PATH . DS . $path1);
            $a=str_replace('\\', '/', $info->getSaveName());
            $q = explode ( '/', $a); 
            $b = strtolower ( $q [count ( $q ) - 1] );
             $path = '/uploads'.  '/' . $idnumber . '/' . $a;
             $real_path=substr($path, 0, strripos($path, '/')) . '/'.$b;
            $data = 
            [
            'file_name'   =>  $name,
            'user_idnumber'  =>$idnumber,
            'user_name'   =>  $username,
            'create_time' =>  date('Y-m-d H-i-s'),
            'real_path'   =>  $real_path,
            'type'        =>  $file_ext,
            'size'        =>  $file->getInfo()['size'],
            'real_name'   =>  trim(strrchr($path, '/'),'/'),
            ];
            $res=Db::table('oa_admin_files')
            ->where('user_idnumber',$idnumber)
            ->find();
            if($res){
                Db::table('oa_admin_files')
                ->where('user_idnumber',$idnumber)
                ->delete();
                 Db::table('oa_admin_files')
               ->insert($data);
            }else{
               Db::table('oa_admin_files')
               ->insert($data);
             }
            return resultArray(['data' => $data]); 
        }else{
            return resultArray(['error' => '上传失败']);
        }
    }*/
/*        public function TeacherImport()
    {

        header('Access-Control-Allow-Methods: POST');
        $file = request()->file('file');
        if (!$file) {
          return resultArray(['error' => '未选择文件']);
        }
        $name = substr($file->getInfo()['name'], 0, strripos($file->getInfo()['name'], '.'));
        $filenameArr = explode ( '.', $file->getInfo()['name']); 
        $file_ext = strtolower ( $filenameArr [count ( $filenameArr ) - 1] );
        if($file_ext=='xlsx'||$file_ext=='xls')
        {
          $path1="uploads/";
          $info = $file->validate(['ext'=>'xlsx,xls'])->move(ROOT_PATH . DS . $path1);
            $a=str_replace('\\', '/', $info->getSaveName());
            $q = explode ( '/', $a); 
            $b = strtolower ( $q [count ( $q ) - 1] );
             $path = '/uploads'. '/' . $a;
             $real_path=substr($path, 0, strripos($path, '/')) . '/'.$b;
           }else{
            return resultArray(['error'=>'文件上传格式错误']);
           }
                vendor("PHPExcel.PHPExcel");
                $result=$this->readExcel(ROOT_PATH . DS . $real_path);
                $trains=array();
                foreach ($result as $key => $v) 
                {   
                    $train=array();
                    $traindata=array();
                    $train['name']=$v[0];
                    $train['idnumber'] = $v[1];
                    $train['password']=$v[2];
                    $train['sex']=$v[3];
                    $train['nation']=$v[4];
                    $train['birth']=$v[5];
                    $train['edu']=$v[6];
                    $train['degree']=$v[7];
                    $train['politics']=$v[8];
                    $train['preoccupation']=$v[9]; 
                    $train['majoroccupation']=$v[10];
                    $train['majortime']=$v[11];                  
                    $train['sch']=$v[12];
                    $train['jobrank']=$v[13];
                    $train['address']=$v[14];
                    $train['postalcode']=$v[15];
                    $train['office']=$v[16];
                    $train['phone']=$v[17];
                    $train['qq']=$v[18];
                    $train['fax']=$v[19];
                    $train['email']=$v[20];
                    //判断男女，男1女2
                    if($v[3]=="男")
                    {
                         $train['sex']=1;
                    }
                    else if($v[3]=="女")
                    {
                         $train['sex']=2;
                    }
                    else
                    {
                      $train['sex']=null;
                    }
                    //判断密码是否为空，为空则默认123456；
                    if (!empty($train['password'])) {
                         $train['password'] = user_md5($train['password']);
                      }else{
                        $train['password']='d93a5def7511da3d0f2d171d9c344e91';
                      }



                        
                  //写入数据库
                  
                    $info=array();
                    $infoa=array();
                    $infob=array();
                   $traindata=Db::table('oa_admin_train')
                          ->where('idnumber',$train['idnumber'])
                          ->where('name',$train['name'])
                          ->find();
                       if($traindata){
                                  $reason='此人已存在';
                                 $a=$train['name'].$reason;

                                  return $a;
                          }else{   $info['name']=$train['name'];
                                   $info['idnumber']=$train['idnumber']; 
                                   $info['sex']=$train['sex'];
                                   $info['nation']=$train['nation'];
                                   if (!empty($train['birth'])) {
                                   $info['birth']=$train['birth'];
                                 }
                                   $info['politics']=$train['politics']; 
                                   $info['sch']=$train['sch']; 
                                   $info['preoccupation']=$train['preoccupation']; 
                                   $info['majoroccupation']=$train['majoroccupation'];
                                   if (!empty($train['majortime'])) {
                                   $info['majortime']=$train['majortime'];
                                 }
                                   $info['jobrank']=$train['jobrank'];
                                   $info['edu']=$train['edu'];
                                   $info['degree']=$train['degree'];
                                   $info['address']=$train['address'];
                                   $info['postalcode']=$train['postalcode'];
                                   $info['office']=$train['office'];
                                   $info['phone']=$train['phone'];
                                   $info['qq']=$train['qq'];
                                   $info['email']=$train['email'];
                                   $info['status']=1;
                                   $info['status1']=1;
                                   $info['submit']=1;
                                   $info['updata_time']=date('Y-m-d');

                                      Db::table('oa_admin_train')
                                             ->insert($info);
                                  $infoa['username']=$train['idnumber'];
                                  $infoa['password']=$train['password'];
                                  $infoa['create_time']=time();
                                  $infoa['realname']=$train['name'];
                                  $infoa['status']=1;
                                  $infoa['level']=1;
                                  Db::table('oa_admin_user')
                                             ->insert($infoa);
                                  $userId = Db::name('user')->getLastInsID();
                                  $infob['user_id']=$userId;
                                  $infob['group_id']=18;
                                  Db::table('oa_admin_access')
                                             ->insert($infob);
                          }
               } 
                unlink(ROOT_PATH . DS . $real_path);
                return resultArray(['data'=>'导入成功']);  

        
      }*/
    

    function readExcel($filename, $encode = 'utf-8')
    {
      
        vendor("PHPExcel.PHPExcel");
        $fileType=\PHPExcel_IOFactory::identify($filename);//自动获取文件的类型提供给phpexcel用
        $objReader = \PHPExcel_IOFactory::createReader($fileType);
        $objReader->setReadDataOnly(true);

        $objPHPExcel = $objReader->load($filename);
        $objActsheet = $objPHPExcel->getActiveSheet();

        $highestRow = $objActsheet->getHighestRow();
        $highestColumn = $objActsheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();

        for ($row = 3; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row-1][] = (string) $objActsheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }

        return $excelData;
    }

   function findValueByKey($arr, $key, $val)
   {
    foreach ($arr as $k => $v) 
    {
        if ($v[$key] == $val) 
        {
            return $v;
        }
    }
    return false;
   }

/*   function intrain($number)
   {
    $data = Db::table('oa_admin_train')->where('number', $number)->find();
    if ($data) {
      return true;
    } else {
      return false;
    }
   }*/
   function istime($date)
   {
     if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
            if (checkdate( $parts[2], $parts[3], $parts[1])) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

   }
}